import { defineStore } from 'pinia'
import { reactive} from 'vue'
import {getPaging} from '@/api/disk/file'
import SparkMD5 from 'spark-md5';
import {clickFolder} from '@/api/disk/file'

function initState(){
  return {
    fileList: [],//文件列表(已经分好页)
    currentFiles: [],//当前选择的文件
    showButton: false,//当为true时候，证明选择了文件，显示删除修改等按钮
    total: 0,//总文件数
    currentBread: [],//当前面包屑
    currentMenuIndex: null,//当前菜单索引
    loading: false,//文件列表加载状态
    currentPage: 1,//当前页
    pageSize: 20,//每页显示条数
    showPopup: false,//文件传输列表状态
    uploadList: [], //文件上传列表
    deleteList: [], //文件删除列表
    dialogVisible: false,//预览弹窗状态
    previewUrl: '',//预览文件url
    currentFolderPaht: '/',//当前文件夹路径,标识点击文件夹的时候的标志
    currentClickFile: null,//当前点击的文件或者文件夹
  }
}

export const fileStore = defineStore('file', (a) => {
      const state=reactive(initState())
      
      //改变按钮显示状态
      function changeShowButton(val){
        state.showButton=val
      }
      //新增文件夹
      function addFileList(val){
        //把新增的文件添加到文件列表中第一个 unshift用于在数组的开头添加一个或多个元素
        state.fileList.unshift(val)
      }
      //初始化文件列表
      async function initFileList(){
        state.showButton=false
        state.loading=true
        const res=await getPaging(state.currentPage,state.pageSize,state.currentMenuIndex)
        state.fileList=res.rows
        state.total=res.total
        setTimeout(() => {
            state.loading=false
        }, 200) 
      }
      //点击文件夹更新文件列表
      async function updateFileList(file){
        state.showButton=false
        state.loading=true
        const data={
          filePath: file.filePath,
          folderName: file.fileName,
          pageNum: state.currentPage,
          pageSize: state.pageSize,
        }
        //记录当前已经点击文件夹的路径
        state.currentFolderPaht=file.filePath
        //记录当前点击的文件夹
        state.currentClickFile=file
        const res= await clickFolder(data)
        state.fileList=res.rows
        //更新分页信息
        state.total=res.total
        setTimeout(() => {
            state.loading=false
        }, 200) 
      }
      //更新面包屑路径
      function updateCurrentBread(val){
        if(val){
          state.currentBread.push(val)
        }else{
          state.currentBread=[]
        }
        
      }
      //删除指定面包屑
      function deleteBreadPop(item){
        //找到当前面包屑的索引
        const index=state.currentBread.findIndex(i=>i.id===item.id)
        //删除当前索引之后的全部元素
        state.currentBread.splice(index+1)
      }
      //更新当前页以及每页显示条数
      function updateCurrentPage(val){
        state.currentPage=val
      }
      //更新当前菜单索引
      function updateCurrentMenuIndex(val){
        state.currentMenuIndex=val
      }
      //计算文件的MD5值
      async function calculateMD5(file) {
        return new Promise((resolve, reject) => {
          const fileReader = new FileReader();
          const spark = new SparkMD5.ArrayBuffer();

          fileReader.onload = function (e) {
            spark.append(e.target.result);
            const md5 = spark.end();
            resolve(md5);
          };

          fileReader.onerror = function (error) {
            reject(error);
          };

          fileReader.readAsArrayBuffer(file);
        });
      }
      //更新文件传输弹窗状态
      function updateShowPopup(val){
        state.showPopup=val
      }
      //添加文件上传列表
      function addToUploadList(file,uid){
        state.uploadList.unshift({
          uid,
          file,
          progress: 0,
          status: 'pending'
        })
      }
      // 新增更新进度方法
      function updateUploadProgress(uid, progress) {
        const item = state.uploadList.find(item => item.uid === uid)
        if (item) {
          item.progress = progress
          item.status = progress === 100 ? 'done' : 'uploading'
        }
      }
      //切割文件为分片
      function sliceFile(file, chunkSize) {
        const chunks = [];
        const totalSize = file.size;
        let start = 0;

        while (start < totalSize) {
          const end = Math.min(start + chunkSize, totalSize);
          const chunk = file.slice(start, end);
          chunks.push(chunk);
          start = end;
        }
        return chunks;
      }
      //更新文件删除列表
      function updateDeleteList(val){
        if(val.length>0){
          state.deleteList=val
        }else{
          state.deleteList=[]
        }
        
      }
      //更新预览弹窗状态
      function updateDialogVisible(val){
        state.dialogVisible=val
      }
      //更新预览文件url
      function updatePreviewUrl(val){
        state.previewUrl=val
      }
      //更新currentFolderPaht
      function updateCurrentFolderPaht(val){
        state.currentFolderPaht=val
      }
      //任意操作文件列表后，重置文件列表
      function resetFileList(){
        if(state.currentFolderPaht==='/'){
          initFileList()
        }else{
          updateFileList(state.currentClickFile)
        }
      }
      //更新当前选择的文件列表
      function updateCurrentFiles(val){
        state.currentFiles=val
      }
      //更新当前点击的文件或者文件夹
      function updateCurrentClickFile(val){
        state.currentClickFile=val
      }
      //通过搜索更新文件列表
      function updateFileListBySearch(val){
        state.fileList=val
      }
      return {
        state,
        changeShowButton,
        addFileList,
        initFileList,
        updateFileList,
        updateCurrentBread,
        deleteBreadPop,
        updateCurrentPage,
        updateCurrentMenuIndex,
        calculateMD5,
        updateShowPopup,
        updateUploadProgress,
        addToUploadList,
        sliceFile,
        updateDeleteList,
        updateDialogVisible,
        updatePreviewUrl,
        resetFileList,
        updateCurrentFolderPaht,
        updateCurrentFiles,
        updateCurrentClickFile,
        updateFileListBySearch
      }
})